package com.lut.edu.apm.payCenter.message.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.lut.edu.apm.payCenter.message.AliMessage;
import com.lut.edu.apm.payCenter.services.RedisService;
import org.apache.logging.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Zhao Suzhen
 * @date `2024/3/29`
 */
@Repository
public class AliMessageImpl implements AliMessage {

    @Autowired
    RedisService redisService;

    private static final Logger LOGGER = LoggerFactory.getLogger(AliMessage.class);

    @Override
    public boolean sendLoginVerificationCode(String phoneNumber) throws Exception {
        String templateCode = "SMS_465333717";
        return aliMessage(templateCode, phoneNumber, randomNumbers());
    }

    @Override
    public boolean verifyVerificationCode(String phoneNumber, String validateCode) throws Exception {
        Object o = redisService.get(phoneNumber);
        if (validateCode.equals(o)) {
            redisService.delete(phoneNumber);
        } else {
            if (null == o){
                LOGGER.info(String.format("用户 %s 验证码过期", phoneNumber));
            }
            return false;
        }
        return true;
    }

    @Override
    public boolean sendRegistrationVerificationCode(String phoneNumber) throws Exception {
        String templateCode = "SMS_465388785";
        return aliMessage(templateCode, phoneNumber, randomNumbers());
    }


    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     */
    private static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    private boolean aliMessage(String messageType, String phoneNumber, int validateCode) throws Exception {
        Map<String, String> codeJson = new HashMap<>();
        codeJson.put("code", String.valueOf(validateCode));
        com.aliyun.dysmsapi20170525.Client client = AliMessageImpl.createClient();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("池胖胖无人超市")
                .setTemplateCode(messageType)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam(JSONObject.toJSONString(codeJson));
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            redisService.setExpire(phoneNumber, String.valueOf(validateCode));
//            LOGGER.info(sendSmsResponse.toString());
            if (sendSmsResponse.getStatusCode() == 200) {
                LOGGER.info(String.format("电话号码：%s,验证码：%s",phoneNumber, validateCode));
                return true;
//                return "OK".equals(sendSmsResponse.body.getMessage());
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            LOGGER.error(error.getMessage());
            // 诊断地址
            LOGGER.error((String) error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            LOGGER.error(error.getMessage());
            // 诊断地址
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return false;
    }

    private int randomNumbers() {
        Random random = new Random();
        return random.nextInt(9000) + 1000;
    }
}
